﻿using ChatTools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ChatTools;
using EntityManage;

namespace ChatClient
{
    public partial class FormFriendsList : Form
    {
        public FormFriendsList()
        {
            InitializeComponent();
            this.client = new Client();
            this.client.RefreshConnectStatus += new EventHandler<ConnectEventArgs>(this.Client_RefreshConnectStatus);
            this.client.DataReceive += new EventHandler<ReceiveEventArgs>(this.Client_DataReceive);
            this.Load += FormFriendsList_Load;
        }

        public FormFriendsList(int id, string loginid, string nickname)
            : this()
        {
            _id = id;
            _loginid = loginid;
            _nickname = nickname;
        }

        private int _id;
        private string _loginid, _nickname;
        private const int SERVER_PORT = 20255;
        private Client client;
        private int _friendid;
        private List<FormClient> chatClients = new List<FormClient>();
        private Dictionary<int, string> friends = new Dictionary<int, string>();

        private void FormFriendsList_Load(object sender, EventArgs e)
        {
            lblNickName.Text = _nickname;
            this.lblStatus.Text = "正在连接服务器...";
            this.probar.Visible = true;
            this.client.Connect("127.0.0.1", SERVER_PORT, _id);
            LoadFriendList();

        }

        private void LoadFriendList()
        {
            friends = UserManager.GetFriendsList(_id);
            treeFriends.Nodes.Clear();
            foreach (var friend in friends)
            {
                TreeNode node = new TreeNode(friend.Value);
                node.Tag = friend.Key;
                treeFriends.Nodes.Add(node);
            }
        }

        private void Client_RefreshConnectStatus(object sender, ConnectEventArgs e)
        {
            if (e.Connected)
                this.Invoke((Action)(() =>
                {
                    this.lblStatus.Text = "服务器已连接";
                    this.probar.Visible = false;
                }));
            else
                this.Invoke((Action)(() =>
                {
                    this.lblStatus.Text = "正在连接服务器...";
                    this.probar.Visible = true;
                }));
        }

        private void Client_DataReceive(object sender, ReceiveEventArgs e)
        {
            this.Invoke((Action)(() =>
            {
                string str = e.Text;
                string[] strArray = str.Split(new char[1] { '|' });
                int type = int.Parse(strArray[0]);
                int sendid = int.Parse(strArray[1]);
                int receiveid = int.Parse(strArray[2]);
                string msg = strArray[3]; ;
                bool hasChat = false;
                foreach (FormClient formChat in chatClients)
                {
                    if (formChat._friendID == sendid)
                    {
                        formChat.AppendMsg(msg);
                        hasChat = true;
                        break;
                    }
                }
                if (!hasChat)
                {
                    FormClient client = new FormClient(sendid, friends[sendid], _nickname);
                    client.StartPosition = FormStartPosition.CenterParent;
                    client.SendMsg += new EventHandler(Client_SendMsg);
                    client.StartPosition = FormStartPosition.CenterParent;
                    client.Text = friends[sendid];
                    client.FormClosing +=
                        (object s, FormClosingEventArgs ee) =>
                        {
                            chatClients.Remove(client);
                        };
                    client.Show();
                    client.AppendMsg(msg);
                    chatClients.Add(client);
                }
            }));
        }



        private void Client_SendMsg(object sender, EventArgs e)
        {
            FormClient formChat = sender as FormClient;
            string msg = formChat.GetMsg();
            string str = string.Format("{0}|{1}|{2}|{3}", 1, _id, formChat._friendID, msg);
            this.client.Send(str);

        }

        private void btnAddFriend_Click(object sender, EventArgs e)
        {
            FormAddFriend formAddFriend = new FormAddFriend(_id, _nickname);
            formAddFriend.StartPosition = FormStartPosition.CenterParent;
            if (formAddFriend.ShowDialog() == DialogResult.OK)
            {
                LoadFriendList();
            }
        }

        private void treeFriends_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            bool hasChat = false;
            foreach (FormClient formChat in chatClients)
            {
                if (formChat._friendID == (int)node.Tag)
                {
                    formChat.Show();
                    hasChat = true;
                    break;
                }
            }
            if (!hasChat)
            {
                FormClient client = new FormClient((int)node.Tag, node.Text, _nickname);
                client.StartPosition = FormStartPosition.CenterParent;
                client.SendMsg += new EventHandler(Client_SendMsg);
                client.Text = node.Text;
                client.FormClosing +=
                    (object s, FormClosingEventArgs ee) =>
                    {
                        chatClients.Remove(client);
                    };
                client.Show();
                chatClients.Add(client);
            }
        }

        private void lblNickName_DoubleClick(object sender, EventArgs e)
        {
            FormEditNickname form = new FormEditNickname(_id);
            if (form.ShowDialog() == DialogResult.OK)
            {
                lblNickName.Text = form.NickName;
            }
        }

        private void FormFriendsList_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.ExitThread();
            Application.Exit();
        }
    }
}
